<template>
  <div>
    <!-- 顶部的部分 -->
    <div id="samplesFixed" :class="{'samples-fixed' : isFixed}">
      <el-row class="samples-info-box insert-page">
        <el-col :span="15">
          <h2>新增合同</h2>
        </el-col>
        <!-- 右半边按钮区域 -->
        <el-col :span="9" class="samples-text-right">
          <el-button size="mini" plain type="success" @click="submitForm('ruleForm','save')">暂 存</el-button>
          <el-button size="mini" type="primary" plain @click="cancel">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </el-col>
      </el-row>
    </div>

    <el-row>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        class="samples-form"
        :rules="rules"
        label-width="140px"
      >
        <div class="samples-info-box samples-pageForm">
          <span class="title">基本信息</span>
          <el-row class="samples-dialog-form">
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同分类：" prop="classifyId">
                <el-select
                  v-model="ruleForm.classifyId"
                  clearable
                  style="width:100%"
                  placeholder="请选择合同分类"
                  size="small"
                  @change="selectClassifyName"
                  @clear="clearClassifyName"
                >
                  <el-option
                    v-for="item in classifyNameList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同类型：" prop="typeId">
                <el-select
                  v-model="ruleForm.typeId"
                  clearable
                  style="width:100%"
                  placeholder="请选择合同类型"
                  size="small"
                  @change="selectTypeName"
                  @clear="clearTypeName"
                >
                  <el-option
                    v-for="item in typeNameList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col :lg="12" :xl="8">
              <el-form-item label="合同编号：" prop="code">
                <el-input v-model="ruleForm.code" clearable placeholder="请输入合同编号" size="small" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同名称：" prop="name">
                <el-input v-model="ruleForm.name" clearable placeholder="请输入合同名称" size="small" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col v-if="ruleForm.classifyId == &quot;001202&quot;" :lg="12" :xl="8">
              <el-form-item label="项目名称：" prop="projectName">
                <el-input
                  v-model="ruleForm.projectName"
                  clearable
                  placeholder="请输入项目名称"
                  size="small"
                />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item prop="partyAId" label="甲方名称：">
                <el-select
                  v-model="ruleForm.partyAId"
                  filterable
                  remote
                  clearable
                  style="width: 100%;"
                  size="small"
                  class="samples-must-declared"
                  placeholder="请输入甲方名称"
                  :remote-method="querySearch"
                  popper-class="select-dropdown-width"
                  @change="getSelectPartyANameList"
                >
                  <el-option
                    v-for="item in partyANameList_temp"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col :lg="12" :xl="8">
              <el-form-item clearable prop="partyBId" label="乙方名称：">
                <el-select
                  v-model="ruleForm.partyBId"
                  filterable
                  remote
                  style="width: 100%;"
                  class="inline-input"
                  size="small"
                  clearable
                  placeholder="请输入乙方名称"
                  :remote-method="querySearchTwo"
                  popper-class="select-dropdown-width"
                  @change="getSelectPartyBNameList"
                >
                  <el-option
                    v-for="item in partyBNameList_temp"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
                <!-- <el-autocomplete
                  v-model="ruleForm.partyBName"
                  style='width: 100%;'
                  class="inline-input"
                  :fetch-suggestions="querySearchTwo"
                  placeholder="请输入乙方名称"
                  :trigger-on-focus="false"
                  clearable
                  size="small"
                  @select="handleSelectTwo"
                />-->
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="业务单元：" prop="businessUnitId">
                <el-select
                  v-model="ruleForm.businessUnitId"
                  style="width: 100%;"
                  size="small"
                  placeholder="请选择业务单元"
                  clearable
                >
                  <el-option
                    v-for="item in unitList"
                    :key="item.deptId"
                    :label="item.name"
                    :value="item.deptId"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同金额：" prop="amount">
                <el-popover
                  ref="popover1"
                  popper-class="samples-input-popper-class"
                  placement="top"
                  trigger="focus"
                  :content="value11"
                />
                <el-input
                  v-model="ruleForm.amount"
                  v-popover:popover1
                  size="small"
                  placeholder="请输入合同金额"
                  clearable
                  @input="fmoney1(ruleForm.amount)"
                />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="签约时间：" prop="signedTime">
                <el-date-picker
                  v-model="ruleForm.signedTime"
                  type="date"
                  style="width:100%"
                  value-format="yyyy-MM-dd"
                  size="small"
                  placeholder="选择签约时间"
                  clearable
                />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :lg="24" :xl="{span: 16, offset: 1,pull:1}">
              <el-form-item label="合同内容：" prop="content">
                <el-input
                  v-model="ruleForm.content"
                  clearable
                  type="textarea"
                  maxlength="500"
                  resize="none"
                  size="small"
                  :autosize="{ minRows: 4, maxRows: 10}"
                  placeholder="请输入合同内容"
                />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="samples-info-box samples-pageForm">
          <el-row style="margin-bottom: 15px;">
            <el-col :span="15">
              <span class="title">合同信息</span>
            </el-col>
            <el-col
              v-show="ruleForm.classifyId != false && ruleForm.typeId != false && ruleForm.classifyId != null && ruleForm.typeId != null"
              :span="9"
              class="samples-text-right"
            >
              <el-button size="mini" type="primary" plain @click="chooseContract">选择合同</el-button>
            </el-col>
          </el-row>

          <el-row class="samples-dialog-form">
            <el-table :data="contractTable" style="width: 100%">
              <el-table-column prop="code" label="合同编号" width="180" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>
                    <a
                      style="display: block; color: #ceab70;text-decoration-line: underline;"
                      class="samples-table-overflow"
                      @click="toRouter('code',scope)"
                    >{{ scope.row.code }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="合同名称" width="180" show-overflow-tooltip />
              <el-table-column prop="partyAName" label="甲方单位" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>
                    <div>{{ scope.row.partyAName }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="partyBName" label="乙方单位" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>
                    <div>{{ scope.row.partyBName }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" width="180" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ (Number(scope.row.amount).toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,'$&,') }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="signedTime" label="签订日期" width="180" show-overflow-tooltip />
              <el-table-column prop="typeName" label="合同类型" width="180" show-overflow-tooltip />
              <el-table-column prop="name" label="操作" width="90">
                <template slot-scope="scope">
                  <el-popover placement="left" trigger="click" popper-class="s-popover" width="234">
                    <div
                      style="display:flex;align-items:center;justify-content:center;padding:20px 0;"
                    >
                      <i
                        class="el-icon-question"
                        style="font-size:26px;margin-right:10px;color:#e05e5e"
                      /> 确定删除这条数据吗？
                    </div>
                    <div style="text-align: center; margin: 0">
                      <el-button size="small" type="primary" plain @click="handleClosePopover()">取 消</el-button>
                      <el-button
                        type="primary"
                        size="small"
                        @click="deleteContract(scope.row,scope.$index)"
                      >确 认</el-button>
                    </div>
                    <el-button
                      slot="reference"
                      type="text"
                      style="padding-top: 0;"
                      class="samples-text-button-disabled"
                    >删 除</el-button>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>

        <div
          v-show="Lists.length > 0"
          class="samples-info-box samples-pageForm"
          style="margin-bottom: 10px;"
        >
          <span class="title">附件信息</span>
          <div class="tab-upload-box" style="margin-top: 15px;">
            <el-tabs class="samples-tabs">
              <el-tab-pane v-for="(item , index) in Lists" :key="index">
                <div slot="label" class="tabs-lable">
                  <span>{{ item.name }}</span>
                  <span>({{ fileList[index]?fileList[index].length:0 }})</span>
                </div>
                <upload
                  :action="action"
                  :multiple="false"
                  :file-list="fileList[index]"
                  @removeList="(i)=>{return spliceList(i,index)}"
                  @changeFile="files=>{return changeFileHandler(files,index)}"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <div v-if="isCanMateriel" class="samples-info-box samples-pageForm">
          <el-row style="margin-bottom: 15px;">
            <el-col :span="15">
              <span class="title">物料信息</span>
            </el-col>
            <el-col :span="9" class="samples-text-right">
              <el-button size="mini" type="primary" plain @click="addMatrial">添加物料</el-button>
            </el-col>
          </el-row>
          <el-row class="samples-dialog-form">
            <el-form
              ref="tableForm"
              :model="materielTable"
              :rules="formRules"
              class="samples-dialog-form"
            >
              <el-table :data="materielTable.data" class="contract-materiel" style="width: 100%">
                <el-table-column label="物料名称" width="200" fixed="left">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.materielMust"
                      label-width="0"
                      :prop="`data[${scope.$index}].name`"
                      class="samples-mb-75"
                    >
                      <el-input
                        v-model="scope.row.name"
                        placeholder="物料名称"
                        clearable
                        class="materielTable-input"
                      />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="specification" label="规格" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.materielMust"
                      label-width="0"
                      :prop="`data[${scope.$index}].specification`"
                      class="samples-mb-75"
                    >
                      <el-input
                        v-model="scope.row.specification"
                        placeholder="规格"
                        clearable
                        class="materielTable-input"
                      />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                      <!-- <template slot="error" slot-scope="scope">
                        <el-popover
                          placement="top"
                          width="200"
                          :is-hidden="true"
                          popper-class="sample-error-message materielTable-popper"
                          :content="scope.error"
                        >
                          <div slot="reference" class="table-sample-error-message" />
                      </el-popover></template>-->
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="brand" label="品牌" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.materielMust"
                      label-width="0"
                      :prop="`data[${scope.$index}].brand`"
                      class="samples-mb-75"
                    >
                      <el-input
                        v-model="scope.row.brand"
                        placeholder="品牌"
                        clearable
                        class="materielTable-input"
                      />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="unitId" label="物料单位" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.materielMustUnitId"
                      label-width="0"
                      :prop="`data[${scope.$index}].unitId`"
                      class="samples-mb-75"
                    >
                      <el-select
                        v-model="scope.row.unitId"
                        filterable
                        clearable
                        style="width:100%"
                        placeholder="物料单位"
                        size="small"
                        class="materielTable-input"
                      >
                        <el-option
                          v-for="item in materielNameList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="物料单价" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.priceNumber"
                      label-width="0"
                      :prop="`data[${scope.$index}].price`"
                      class="samples-mb-75"
                    >
                      <el-input
                        v-model="scope.row.price"
                        clearable
                        class="materielTable-input"
                        placeholder="物料单价"
                        @input="changeTotal(scope,scope.row.price,scope.row.number)"
                      />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="物料数量" width="200">
                  <template slot-scope="scope">
                    <el-form-item
                      :rules="formRules.priceNumber"
                      label-width="0"
                      :prop="`data[${scope.$index}].number`"
                      class="samples-mb-75"
                    >
                      <el-input
                        v-model="scope.row.number"
                        clearable
                        class="materielTable-input"
                        placeholder="物料数量"
                        @input="changeTotal(scope,scope.row.price,scope.row.number)"
                      />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="total" label="物料总价">
                  <template slot-scope="scope">
                    <span>{{ scope.row.total }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="操作" width="120" fixed="right">
                  <template slot-scope="scope">
                    <el-popover
                      placement="left"
                      trigger="click"
                      popper-class="s-popover"
                      width="234"
                    >
                      <div
                        style="display:flex;align-items:center;justify-content:center;padding:20px 0;"
                      >
                        <i
                          class="el-icon-question"
                          style="font-size:26px;margin-right:10px;color:#e05e5e"
                        /> 确定删除这条数据吗？
                      </div>
                      <div style="text-align: center; margin: 0">
                        <el-button
                          size="small"
                          type="primary"
                          plain
                          @click="handleClosePopover()"
                        >取 消</el-button>
                        <el-button
                          type="primary"
                          size="small"
                          @click="deleteMatrial(scope.row,scope.$index)"
                        >确 认</el-button>
                      </div>
                      <el-button
                        slot="reference"
                        type="text"
                        style="padding-top: 0;"
                        class="samples-text-button-disabled"
                      >删 除</el-button>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <div class="totalPriceRow">合计金额：{{ totalPrice }}</div>
          </el-row>
        </div>
      </el-form>
    </el-row>

    <el-dialog
      title="选择合同"
      :visible.sync="contractTableQueryVis"
      width="960px"
      top="50vh"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      custom-class="samples-dialog"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <!-- esc按钮和点击遮罩不会关闭弹窗，需要设置配置项 -->
      <el-row class="samples-dialog-box">
        <el-col :span="24">
          <el-row :gutter="10">
            <el-collapse-transition>
              <el-col
                ref="contractSearch"
                :lg="17"
                class="samples-searchBar-wrapper"
                :class="{'samples-show-more':ismore}"
              >
                <el-col :lg="8" :xl="8">
                  <el-input
                    v-model="contractSearch.code"
                    size="small"
                    placeholder="合同编码"
                    clearable
                    class="samples-search-input"
                  />
                </el-col>
                <el-col :lg="8" :xl="8">
                  <el-input
                    v-model="contractSearch.name"
                    size="small"
                    placeholder="合同名称"
                    clearable
                    class="samples-search-input"
                  />
                </el-col>
                <el-col :lg="8" :xl="8">
                  <el-autocomplete
                    v-model="contractSearch.unitName"
                    size="small"
                    clearable
                    class="inline-input"
                    :fetch-suggestions="querySearchThree"
                    value-key="companyName"
                    placeholder="单位名称"
                    :trigger-on-focus="false"
                    @select="handleSelectThree"
                  />
                  <!-- <el-select
                    v-model="contractSearch.unitName"
                    filterable
                    remote
                    clearable
                    style="width: 100%;"
                    size="small"
                    class="samples-must-declared"
                    placeholder="单位名称"
                    :remote-method="querySearchThree"
                    popper-class='select-dropdown-width'
                  >
                    <el-option
                        v-for="item in unitNameList"
                        :key="item.companyId"
                        :label="item.companyName"
                        :value="item.companyName"
                    />
                  </el-select>-->
                </el-col>

                <el-col :lg="16" :xl="16">
                  <el-date-picker
                    v-model="contractSearch.time"
                    size="small"
                    style="width:100%"
                    type="daterange"
                    range-separator="至"
                    value-format="yyyy-MM-dd"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-col>
              </el-col>
            </el-collapse-transition>
            <el-col :lg="7">
              <el-button
                size="small"
                type="primary"
                plain
                class="samples-search-btn"
                @click="searchContract()"
              >
                <i class="el-icon-search" />
              </el-button>
              <el-button
                size="small"
                type="text"
                class="samples-search-btn samples-ismore-button"
                @click="moreClick"
              >
                MORE
                <i
                  class="samples-search-icon"
                  :class="[ismore?'el-icon-arrow-up':'el-icon-arrow-down']"
                />
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row class="samples-dialog-box" style="max-height: 600px;overflow: auto;padding-top: 0px;">
        <s-table
          ref="multipleTable"
          :column="contractTableQuery.column"
          :data="contractTableQuery.data"
          :header-cell-class-name="headerCellClass"
          pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,50]"
          :current-page.sync="contractSearch.page"
          :total="total"
          :page-size="contractSearch.pageSize"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @p-current-change="handleCurrentChange"
        />
      </el-row>
      <el-row class="samples-dialog-footer samples-mt-20">
        <el-row class="samples-float-right">
          <el-button size="small" type="primary" plain @click="handleClose">取 消</el-button>
          <el-button size="small" type="primary" @click="premitChooseContract">提 交</el-button>
        </el-row>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import sTable from "@/components/STable/s-table";
import {
  insertApi,
  queryUnit,
  selectContractApi,
  selectContractTableApi,
  selectMaterialTableApi,
  materialTableApi,
  deleteApi,
  detailApi,
  editApi,
  materialApi,
  getListApi,
  searchJiaYiApi,
  getContractStatusApi,
  operateApi,
  contractMagDictApi,
  getFileTagsApi,
  searchJiaYiNextApi
} from "@/api/contractManage/contractMag";
import upload from "@/components/Supload/upload";
import { cacheMixin } from "@/utils/mixins/clearCache";
import { fixedMixin } from "@/utils/mixins/fixedHeaderMixin";
import axios from "axios";
import * as rulejs from "@/utils/rules";
var reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/;
var numberDittContract = (rule, value, callback) => {
  const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/;
  if (value == "") {
    callback(new Error("请输入"));
  } else if (!reg.test(value) && value != null && value != "") {
    callback(new Error("请输入纯数字，支持小数点后四位"));
  } else {
    callback();
  }
};
var numberDittContractSave = (rule, value, callback) => {
  const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/;
  if (!reg.test(value) && value != null && value != "") {
    callback(new Error("请输入纯数字，支持小数点后四位"));
  } else {
    callback();
  }
};

export default {
  components: {
    upload,
    sTable
  },
  mixins: [cacheMixin, fixedMixin],
  data() {
    return {
      value11: "",
      errorVisible: true,
      formRules: {
        materielMust: [{ required: true, message: "请输入", trigger: "blur" }],
        priceNumber: [
          { required: true, message: "请输入", trigger: "blur" },
          { validator: numberDittContract, trigger: "blur" }
        ],
        materielMustUnitId: [
          { required: true, message: "请选择", trigger: "change" }
        ]
      },
      unitNameList: "",
      establishTime: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
        }
      },
      isCanMateriel: false,
      isFixed: false,
      partyANameList: [],
      partyBNameList: [],
      partyANameList_temp: [],
      partyBNameList_temp: [],
      fileList: [],
      totalPrice: 0,
      Lists: [],
      materielNameList: [],
      total: 0, // 分页
      ismore: false,
      multipleSelection: [],
      contractSearch: {
        code: "",
        name: "",
        unitName: "",
        beginTime: "",
        endTime: "",
        page: 1,
        pageSize: 10,
        classifyId: ""
      },
      contractTable: [],
      contractTableQueryVis: false,
      contractTableQuery: {
        column: [
          {
            type: "selection",
            width: "54"
          },
          {
            prop: "code",
            label: "合同编号",
            width: "150",
            showOverflowTooltip: true
          },
          {
            prop: "name",
            label: "合同名称",
            showOverflowTooltip: true
          },
          {
            prop: "partyAName",
            label: "甲方单位",
            showOverflowTooltip: true
          },
          {
            prop: "partyBName",
            label: "乙方单位",
            showOverflowTooltip: true
          },
          {
            prop: "amount",
            label: "金额（万元）",
            width: "120",
            showOverflowTooltip: true
          },
          {
            prop: "signedTime",
            label: "签订日期",
            width: "140"
          },
          {
            prop: "typeName",
            label: "合同类型",
            width: "90"
          }
        ],
        data: []
      },
      materielTableVis: false,
      materielTable: {
        // data: [{
        //   name: '',
        //   specification: '',
        //   brand: '',
        //   unitId: '',
        //   unitName: '',
        //   price: '',
        //   number: '',
        //   total: ''
        // }]
        data: []
      },
      unitList: [],
      classifyNameList: [],
      typeNameList: [],
      // statusNameList: [
      //   { id: 10, name: '执行中' },
      //   { id: 20, name: '已归档' }
      // ],
      ruleForm: {
        materialAmount: 0,
        amount: 0,
        attachmentList: [], // 附件
        businessUnitName: "", // 业务单元名称
        chooseList: [], // 选择的合同id
        materialList: [], // 物料信息
        classifyName: "", // 业务单元名称
        typeName: "", // 合同类型名称
        partyAId: "", // 甲名称
        partyBId: "", // 乙名称
        // statusName:'',//状态名称
        //
        classifyId: "",
        typeId: "",
        code: "",
        name: "",
        projectName: "",
        partyAName: "",
        partyBName: "",
        businessUnitId: "",
        amount: "",
        signedTime: "",
        // status:'',
        content: ""
      },
      // 表单验证规则
      //   materialRules:{
      //     price: [
      //       { validator: numAddLetter, trigger: 'blur' },
      //     ]

      //   },
      rules: {
        classifyId: [
          {
            required: true,
            message: "请选择合同分类",
            trigger: "change"
          }
        ],
        typeId: [
          {
            required: true,
            message: "请选择合同类型",
            trigger: "change"
          }
        ],
        name: [
          {
            required: true,
            message: "请输入合同名称",
            trigger: "blur"
          }
        ],
        projectName: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: "blur"
          }
        ],
        partyAId: [
          {
            required: true,
            message: "请输入甲方名称",
            trigger: "change"
          }
        ],
        partyBId: [
          {
            required: true,
            message: "请输入乙方名称",
            trigger: "change"
          }
        ],
        businessUnitId: [
          {
            required: true,
            message: "请选择业务单元",
            trigger: "change"
          }
        ],
        signedTime: [
          {
            required: true,
            message: "请选择签约时间",
            trigger: "change"
          }
        ],
        // status: [
        //   { required: true, message: '请选择合同状态', trigger: 'change' },
        // ],
        content: [
          {
            min: 0,
            max: 500,
            message: "不能超过500字符",
            trigger: "blur"
          }
        ],
        amount: [
          {
            required: true,
            message: "请输入合同金额",
            trigger: "blur"
          },
          {
            validator: rulejs.numberMoney,
            trigger: "blur"
          }
        ]
      },
      // status: [], // 企业经营状态
      action: "1"
    };
  },

  computed: {},

  mounted() {
    // 公司类型
    // 查询单位名称

    contractMagDictApi("contract_classify").then(res => {
      this.classifyNameList = res.data;
    });

    queryUnit().then(res => {
      this.unitList = res.data.data;
    });
    materialApi().then(res => {
      if (res.code == 1) {
        this.materielNameList = res.data.data;
      } else {
        this.$notify({
          title: "警告",
          type: "warning",
          message: "查询物料单位接口异常",
          duration: "3000"
        });
      }
    });
  },
  methods: {
    fmoney1(s) {
      if (s == null) {
        return false;
      }
      s = s.toString();
      if (s != "" && typeof s === "string") {
        this.value11 = s.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      } else {
        this.value11 = "";
      }
    },
    toRouter(val, scope) {
      if (val == "code") {
        this.$router.push({
          name: "/contractManage/contractMag/detail",
          params: {
            id: scope.row.id,
            tagsName: scope.row.name
          }
        });
      }
    },
    getSelectPartyANameList() {
      this.partyANameList = this.partyANameList_temp;
    },
    getSelectPartyBNameList() {
      this.partyBNameList = this.partyBNameList_temp;
    },
    clearClassifyName() {
      this.typeNameList = [];
      this.ruleForm.typeId = null;
    },
    selectClassifyName(clear) {
      if (this.ruleForm.classifyId == "001201") {
        contractMagDictApi("single_contract_type").then(res => {
          this.typeNameList = res.data;
        });
      } else if (this.ruleForm.classifyId == "001202") {
        contractMagDictApi("project_contract_type").then(res => {
          this.typeNameList = res.data;
        });
      }
      this.contractTable = []; // 清空合同信息
      this.ruleForm.typeId = null;
    },
    clearTypeName() {
      this.contractTable = [];
      this.Lists = [];
      this.fileList = [];
    },
    selectTypeName() {
      this.contractTable = []; // 清空合同信息
      this.fileList = []; // 清空文件
      this.Lists = []; // 清空文件tag信息
      if (this.ruleForm.typeId == null) {
        this.isCanMateriel = false;
        this.materielTable.data = [
          {
            name: "",
            specification: "",
            brand: "",
            unitId: "",
            price: "",
            number: "",
            total: ""
          }
        ];
        return;
      }
      if (
        this.ruleForm.typeId == "001301" ||
        this.ruleForm.typeId == "001302" ||
        this.ruleForm.typeId == "001304" ||
        this.ruleForm.typeId == "001401" ||
        this.ruleForm.typeId == "001402"
      ) {
        this.isCanMateriel = true;
      } else {
        this.isCanMateriel = false;
        //  this.materielTable.data = [{
        //               name:'',
        //               specification:'',
        //               brand:'',
        //               unitId:'',
        //               price:'',
        //               number:'',
        //               total:''
        //           }]
      }

      this.classifyNameList.forEach(item => {
        if (item.code == this.ruleForm.classifyId) {
          this.ruleForm.classifyName = item.name;
        }
      });

      this.typeNameList.forEach(item => {
        if (item.code == this.ruleForm.typeId) {
          this.ruleForm.typeName = item.name;
        }
      });

      getFileTagsApi({
        classifyName: this.ruleForm.classifyName,
        typeName: this.ruleForm.typeName
      }).then(res => {
        if (res.code == 1) {
          this.Lists = res.data || [];
        } else {
          this.$notify({
            title: "警告",
            type: "warning",
            message: res.msg,
            duration: "3000"
          });
        }
      });
    },
    changeTotal(scope, price, mount) {
      let priceError, numberError;
      this.$refs["tableForm"].validateField(
        `data[${scope.$index}].price`,
        valid => {
          priceError = valid;
        }
      );
      this.$refs["tableForm"].validateField(
        `data[${scope.$index}].number`,
        valid => {
          numberError = valid;
        }
      );
      if (numberError || priceError) {
        scope.row.total = "";
        this.computeTotle();
        return;
      }
      if (price && mount) {
        if (!reg.test(price) || !reg.test(mount)) {
          scope.row.total = "";
          this.computeTotle();
          return;
        }
        scope.row.total = this.toThousands((price * mount).toFixed(2));
        this.computeTotle();
      } else {
        scope.row.total = "";
        this.computeTotle();
      }
    },
    computeTotle() {
      // const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/
      this.totalPrice = 0;
      this.materielTable.data.forEach(item => {
        if (item.total) {
          this.totalPrice = this.toThousands(
            (
              Number((this.totalPrice + "").replace(RegExp(",", "g"), "")) +
              Number((item.total + "").replace(RegExp(",", "g"), ""))
            ).toFixed(2)
          );
        }
      });
    },
    toThousands(num) {
      let mount = num.split(".")[0];
      const temp = mount.length % 3;
      switch (temp) {
        case 1:
          mount = "00" + mount;
          break;
        case 2:
          mount = "0" + mount;
          break;
      }
      return (
        mount
          .match(/\d{3}/g)
          .join(",")
          .replace(/^0+/, "") +
        "." +
        num.split(".")[1]
      );
    },
    addMatrial() {
      this.materielTable.data.push({
        name: "",
        specification: "",
        brand: "",
        unitId: "",
        price: "",
        number: "",
        total: ""
      });
      // this.$set(this.materielTable.data, 1, {
      //     name: '',
      //     specification: '',
      //     brand: '',
      //     unitId: '',
      //     price: '',
      //     number: '',
      //     total: ''
      //   })
      // this.$set(this.materielTable.data, 'checked', true)
    },
    deleteMatrial(row, index) {
      this.materielTable.data.splice(index, 1);
      this.computeTotle();
      this.handleClosePopover();
    },
    deleteContract(row, index) {
      this.contractTable.splice(index, 1);
      this.handleClosePopover();
    },
    premitChooseContract() {
      this.contractTable = this.multipleSelection;
      this.contractTableQueryVis = false;
      this.contractSearch = {
        code: "",
        name: "",
        unitName: "",
        beginTime: "",
        endTime: "",
        page: 1,
        pageSize: 10
      };
    },
    handleClosePopover() {
      document.querySelector("#app").click();
    },
    moreClick() {
      this.ismore = !this.ismore;
      const ref = this.$refs.contractSearch.$el;
      if (this.ismore) {
        ref.style.height = ref.scrollHeight + "px";
      } else {
        ref.style.height = "32px";
      }
    },

    chooseContract() {
      this.contractTableQueryVis = true;
      this.getContractSearchList();
    },
    searchContract() {
      this.contractSearch.page = 1;
      this.getContractSearchList();
    },

    getContractSearchList() {
      const request = Object.assign({}, request, this.contractSearch);
      request.classifyId = this.ruleForm.classifyId;
      request.typeId = this.ruleForm.typeId;
      if (request.time) {
        request.beginTime = request.time[0];
        request.endTime = request.time[1];
      } else {
        request.beginTime = "";
        request.endTime = "";
      }
      this.multipleSelection = [];
      delete request.time;
      selectContractApi(request).then(res => {
        if (res.code == 1) {
          this.contractTableQuery.data = res.data.records;
          this.total = res.data.total;
          this.$nextTick(() => {
            this.contractTable.forEach(item => {
              this.contractTableQuery.data.forEach((item2, index2) => {
                if (item.id == item2.id) {
                  this.multipleSelection.push(item2);
                  this.$refs.multipleTable.toggleRowSelection(item2, true);
                }
              });
            });
          });
        } else {
          this.$notify({
            title: "警告",
            type: "warning",
            message: res.msg,
            duration: "3000"
          });
        }
      });
    },
    handleSizeChange(val) {
      this.contractSearch.pageSize = val;
      this.contractSearch.page = 1;
      this.getContractSearchList();
    },
    handleCurrentChange(val) {
      this.contractSearch.page = val;
      this.getContractSearchList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    headerCellClass({ row, column, rowIndex, columnIndex }) {
      if (column.type === "index") {
        return "indexTableHeaderStyle";
      } else if (column.type === "selection") {
        return "";
      } else {
        return "samples-header-cell";
      }
    },

    handleClose() {
      this.contractTableQueryVis = false;
      //   this.$refs['form'].resetFields()
    },

    handleSelect(item) {},
    handleSelectTwo(item) {},
    handleSelectThree(item) {},

    querySearch(queryString) {
      var query = {
        companyName: queryString
      };
      this.partyANameList_temp = [];
      searchJiaYiApi(query).then(response => {
        this.partyANameList_temp = this.partyANameList_temp.concat(
          response.data.data
        );
      });
      searchJiaYiNextApi(query).then(response => {
        if (response.code == "1") {
          if (response.data.data) {
            this.partyANameList_temp = this.partyANameList_temp.concat(
              response.data.data
            );
          }
        } else {
          this.$notify({
            title: "警告",
            type: "warning",
            message: res.msg,
            duration: "3000"
          });
        }
      });
    },

    querySearchTwo(queryString) {
      var query = {
        companyName: queryString
      };

      this.partyBNameList_temp = [];
      searchJiaYiApi(query).then(response => {
        this.partyBNameList_temp = this.partyBNameList_temp.concat(
          response.data.data
        );
      });
      searchJiaYiNextApi(query).then(response => {
        if (response.code == "1") {
          if (response.data.data) {
            this.partyBNameList_temp = this.partyBNameList_temp.concat(
              response.data.data
            );
          }
        } else {
          this.$notify({
            title: "警告",
            type: "warning",
            message: res.msg,
            duration: "3000"
          });
        }
      });
    },
    querySearchThree(queryString, cb) {
      var query = {
        companyName: queryString
      };
      this.unitNameList = [];
      Promise.all([searchJiaYiApi(query), searchJiaYiNextApi(query)]).then(
        res => {
          if (res[1].code == 1 && res[1].data.data) {
            this.unitNameList = this.unitNameList
              .concat(res[0].data.data)
              .concat(res[1].data.data);
            cb(this.unitNameList);
          } else {
            this.$notify({
              title: "警告",
              type: "warning",
              message: "查询失败",
              duration: "3000"
            });
            return;
          }
        }
      );
    },
    cancel() {
      // debugger
      this.clearCache("contractMag/insert");
      this.closeTag("/contractManage/contractMag");
    },
    resetSaveRules() {
      this.formRules = {
        materielMust: [{ required: true, message: "请输入", trigger: "blur" }],
        priceNumber: [
          { required: true, message: "请输入", trigger: "blur" },
          { validator: numberDittContract, trigger: "blur" }
        ],
        materielMustUnitId: [
          { required: true, message: "请选择", trigger: "change" }
        ]
      };
    },
    submitForm(ruleForm, save) {
      if (save == "save") {
        if (this.isCanMateriel) {
          this.formRules = {
            materielMust: [
              { required: false, message: "请输入", trigger: "blur" }
            ],
            priceNumber: [
              { required: false, message: "请输入", trigger: "blur" },
              { validator: numberDittContractSave, trigger: "blur" }
            ],
            materielMustUnitId: [
              { required: false, message: "请选择", trigger: "change" }
            ]
          };
          this.$nextTick(() => {
            this.$refs["tableForm"].validate(validTableForm => {
              if (validTableForm) {
                this.premitContract(ruleForm, save);
              } else {
                this.resetSaveRules();
              }
            });
          });
        } else {
          this.premitContract(ruleForm, save);
        }
      } else {
        this.$refs[ruleForm].validate(valid => {
          let isPass = true;
          if (this.isCanMateriel) {
            this.$refs["tableForm"].validate(validTableForm => {
              if (!validTableForm) {
                // this.$nextTick(() => {
                //   const element = document.getElementsByClassName('table-sample-error-message')
                //   debugger
                //   // for(let i=0 ;i < element.length;i++){

                //     document.getElementsByClassName('table-sample-error-message')[0].click()

                //     // }
                //   //   element.forEach((item, index) => {
                //   //   item.click()
                //   // })
                // })

                isPass = false;
              }
            });
          }
          if (valid && isPass) {
            this.premitContract(ruleForm, save);
          }
        });
      }
    },
    premitContract(ruleForm, save) {
      const request = Object.assign({}, request, this.ruleForm);
      let message;
      if (save == "save") {
        request.tempFlag = 0;
        request.statusName = "草稿";
        request.status = 1;
        message = "暂存成功";
      } else {
        request.tempFlag = 1;
        request.statusName = "执行中";
        request.status = 10;
        message = "添加成功";
      }

      if (request.classifyId != 0 && !request.classifyId) {
        request.classifyName = "";
      }
      if ((request.typeId != 0 && !request.typeId) || !request.typeId) {
        request.typeName = "";
      }

      if (request.businessUnitId == 0 || request.businessUnitId) {
        this.unitList.forEach(item => {
          if (item.deptId == request.businessUnitId) {
            request.businessUnitName = item.name;
          }
        });
      } else {
        request.businessUnitName = "";
      }

      request.materialAmount = String(this.totalPrice).replace(
        RegExp(",", "g"),
        ""
      );
      if (request.partyAId == 0 || request.partyAId) {
        this.partyANameList.forEach(item => {
          if (item.companyId == request.partyAId) {
            request.partyAName = item.companyName;
          }
        });
      } else {
        request.partyAName = "";
      }

      if (request.partyBId == 0 || request.partyBId) {
        this.partyBNameList.forEach(item => {
          if (item.companyId == request.partyBId) {
            request.partyBName = item.companyName;
          }
        });
      } else {
        request.partyBName = "";
      }

      // request.amount= this.totalPrice//不是这个合同金额
      // 附件整理格式
      request.attachmentList = [];
      if (this.fileList.length > 0) {
        this.fileList.forEach((item, index) => {
          this.Lists.forEach((item2, index2) => {
            if (index == index2) {
              if (item != undefined) {
                item.forEach((item3, index3) => {
                  item3.typeItemId = item2.id;
                  item3.typeItemName = item2.name;
                  item3.fileId = item3.fileUrl;
                  item3.fileName = item3.name;
                  request.attachmentList.push(item3);
                });
              }
            }
          });
        });
      }

      // this.unitList.forEach(item => {
      //   if(item.id == request.businessUnitId){
      //       request.businessUnitName= item.name
      //   }
      // });

      request.chooseList = [];
      this.contractTable.forEach(item => {
        request.chooseList.push(item.id);
      });

      // 物料整理格式
      this.materielNameList.forEach(item => {
        this.materielTable.data.forEach(item2 => {
          if (item.id == item2.unitId) {
            item2.unitName = item.name;
          }
        });
      });

      request.materialList = [];
      request.currency = "人民币";
      if (!request.signedTime) request.signedTime = null;

      this.materielTable.data.forEach(item => {
        item.total = String(item.total).replace(RegExp(",", "g"), "");
        if (
          !Object.values(item).every(valueItem => {
            return valueItem == false;
          })
        ) {
          request.materialList.push(item);
        }
      });

      // this.statusNameList.forEach(item => {
      //   if(item.id == request.status){
      //       request.statusName= item.name
      //   }
      // });

      insertApi(request).then(res => {
        if (res.code == 1) {
          this.$notify({
            title: "成功",
            message: message,
            type: "success",
            duration: 2000
          });

          this.clearCache("contractMag/insert");
          this.closeTag("/contractManage/contractMag");
        } else {
          this.resetSaveRules();
          this.$notify({
            title: "警告",
            type: "warning",
            message: res.msg,
            duration: "3000"
          });
        }
      });
    },

    changeFileHandler(files, index) {
      this.$set(this.fileList, index, files);
    },
    spliceList(i, index) {
      const filelist = JSON.parse(JSON.stringify(this.fileList[index]));

      filelist.splice(i, 1);

      this.$set(this.fileList, index, filelist);

      const files = [];
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i] !== undefined) {
          for (let j = 0; j < this.fileList[i].length; j++) {
            const obj = {};
            this.fileList[i][j];
            obj.fileId = this.fileList[i][j].fileUrl;
            obj.name = this.fileList[i][j].name;
            obj.size = this.fileList[i][j].size;
            // obj.type = this.Lists[i].nodeName
            // obj.companyId = this.editForm.id
            files.push(obj);
          }
        }
      }
      updateFile(files).then(res => {
        if (res.code == "0") {
          // this.getCustomerinfo(this.editForm.id);
        } else {
          this.$notify({
            title: "错误",
            type: "error",
            message: res.msg
          });
        }
      });
    }
  }
};
</script>
<style lang='scss' scoped>
.projectOneTitle {
  margin-bottom: 20px;
}

.totalPriceRow {
  color: #606266;
  font-size: 14px;
  text-align: right;
  margin-top: 12px;
}
</style>
<style lang='scss'>
.select-dropdown-width {
  width: 390px;
  left: 1478px;
}
</style>
